package com.fz.study.project.service.impl;

import com.fz.study.project.entity.SeckillVoucher;
import com.fz.study.project.entity.Voucher;
import com.fz.study.project.mapper.TbVoucherMapper;
import com.fz.study.project.service.ITbSeckillVoucherService;
import com.fz.study.project.service.ITbVoucherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.fz.study.project.utils.RedisConstants.SECKILL_STOCK_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-02-28
 */
@RequiredArgsConstructor
@Service
public class VoucherServiceImpl extends ServiceImpl<TbVoucherMapper, Voucher> implements ITbVoucherService {

    private final ITbSeckillVoucherService seckillVoucherService;

    private final StringRedisTemplate stringRedisTemplate;

    @Transactional
    @Override
    public void addSeckillVocher(Voucher voucher) {
        save(voucher);

        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(seckillVoucher);

//        将库存信息添加到redis中
        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY+voucher.getId(),voucher.getStock().toString());
    }
}
